javascript: var tiku = 1;
var title = '';
if (window.location.href.match(/gxpf.cn/) && window.location.href.match(/login/)) {
    get_verify_code(function() {
        $('#btnLogin').click();
    });
} else if (window.location.href.match(/gxpf.cn/)) {
    is_jQuery();
} else {
    window.location.href = 'https://exam.gxpf.cn/login.html';
}

function is_jQuery() {
    if (window.jQuery == undefined) {
        var add_jQuery = document.createElement('script');
        add_jQuery.src = "//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js";
        window.jQuery || document.getElementsByTagName('head')[0].appendChild(add_jQuery);
        setTimeout(is_jQuery, 200);
    } else {
        require_crypto();
    }
}

function require_crypto() {
    var url = ["https://cdn.bootcss.com/crypto-js/4.1.1/crypto-js.min.js", "https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js", "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"];
    if (window.CryptoJS == undefined) {
        var add_crypto = document.createElement('script');
        add_crypto.src = url[rd2(0, url.length)];
        window.CryptoJS || document.getElementsByTagName('head')[0].appendChild(add_crypto);
        setTimeout(require_crypto, 200);
    } else {
        title = get_tm();
        var test_text = title.slice(0, 30);
        if (tiku == 0) {
            goto_enc(test_text, 0);
        } else if (tiku == 1) {
            if (title.length > 40) {
                title = title.slice(0, 40)
            }
            post(title);
            console.log('开始~');
        }
    }
}

function rd2(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

function rd(min, max) {
    return (Math.random() * (max - min) + min);
}

function get_tm(text) {
    if (!text) {
        text = $('#subjectName').text().replace(/.+?、/, '');
    }
    if (text.length > 50) {
        text = text.substr(0, 50)
    }
    return text;
}

function post(text) {
    var url = 'https://wx.bsxmxx.com/?Act=cha&t=' + rd(0, 1);
    var subdata = 'Act=cha&ai=普法练习题&name=' + text + '&page=1&soso=4';
    $.ajax({
        global: false,
        type: "POST",
        url: url,
        dataType: "html",
        data: subdata,
        error: function(d) {
            console.log('请求出错了');
        },
        success: function(html) {
            console.clear();
            html = html.replace(/\r|\n/g, '');
            if (html.match(/没有查询到/)) {
                console.log('这题没有找到答案');
                console.log(text);
                var test_text = text.slice(0, 30);
                if (test_text.length > 28 && test_text.match(/（.*）|。/)) { /*test_text = text.slice(0,30).replace(/（.*）|。|\r|\n/g,' ');*/ }
                console.log(test_text);
                goto_enc(test_text, 0);
            } else {
                var tixing = [];
                var tx_arr = html.match(/data-label="题型">.+?<\/td>/g);
                for (var i = 0; i < tx_arr.length; i++) {
                    tixing[i] = tx_arr[i].match(/data-label="题型">(.+?)<\/td>/) && tx_arr[i].match(/data-label="题型">(.+?)<\/td>/)[1];
                }
                var lianxiti = [];
                var lxt_arr = html.match(/data-label="普法练习题">.+?<\/td>/g);
                for (var i = 0; i < lxt_arr.length; i++) {
                    lianxiti[i] = lxt_arr[i].match(/data-label="普法练习题">(.+?)<\/td>/) && lxt_arr[i].match(/data-label="普法练习题">(.+?)<\/td>/)[1];
                }
                var daan = [];
                var da_arr = html.match(/data-label="答案">.+?<\/td>/g);
                console.log(da_arr);
                for (var i = 0; i < da_arr.length; i++) {
                    daan[i] = da_arr[i].match(/data-label="答案">(.+?)<\/td>/) && da_arr[i].match(/data-label="答案">(.+?)<\/td>/)[1].replace(/<.+?>/g, '');
                }
                var tab_json = [],
                    title;
                for (var i = 0; i < tixing.length; i++) {
                    title = '题型：' + tixing[i] + '\n题目：' + lianxiti[i] + ' \n答案：' + daan[i];
                    tab_json[i] = {
                        "题型": tixing[i],
                        "题目": lianxiti[i],
                        "答案": daan[i]
                    };
                    if (tixing[i].match(/单选|判断/)) {
                        select(undefined, daan[i])
                    } else if (tixing[i].match(/多选/)) {
                        select(daan[i]);
                    }
                    console.table(title);
                }
            }
        }
    });
}

function get1(text) {
    text = encodeURI(text);
    var url = 'https://tiku.baidu.com/buguakewap/proxy/bgk/bigque/getwapquesearch?query=' + text + '&na_uncheck=1&wk_cs_app=1&_t=' + new Date().getTime();
    $.ajax({
        global: false,
        type: "get",
        url: url,
        dataType: "json",
        error: function(d) {
            console.log('请求出错了');
        },
        success: function(json) {
            var str;
            console.log(json);
            obj_find(json, function(msg) {
                console.log(msg);
                str = msg;
            });
            if (str) {
                get2(str)
            }
        }
    });
}

function get2(str) {
    var url = 'https://tiku.baidu.com/buguakewap/browse/index?qid=' + str + '&limitSwitch=1&limitTimes=3';
    $.ajax({
        global: false,
        type: "get",
        url: url,
        dataType: "html",
        error: function(d) {
            console.log('请求出错了');
        },
        success: function(html) {
            html = html.replace(/\r|\n|\s/g, '');
            var json = html.match(/window.pageData=(.+?);/) && html.match(/window.pageData=(.+?);/)[1];
            json = JSON.parse(json);
            var ans = json.answerList && json.answerList[0] && json.answerList[0].bdjson;
            ans = decodeUnicode(ans);
            ans = JSON.parse(ans);
            var que = ans.que_stem[0].c[0].c;
            console.log('问题：' + que);
            var que2 = ans.que_stem[1].c[0].c;
            console.log('选项：' + que2);
            var ans2 = ans.que_answer[0].c[0].c;
            console.log('答案：' + ans2);
        }
    });
}

function goto_enc(value, err) {
    console.log('value', value);
    value = value.replace(/\s/g, '');
    var json = {
        code: '',
        key: value,
        usersign: generateRandomHex(32)
    };
    jsenc(json, function(str) {
        if (str) {
            get3(str, err);
        }
    });
}

function get3(str, err) {
    console.clear();
    var url = 'https://zs.51dtsq.com:8300/api/v1/agent/SearchQuestion?content=' + str;
    $.ajax({
        global: false,
        type: "get",
        url: url,
        dataType: "json",
        error: function(d) {
            console.log('请求出错了');
        },
        success: function(json) {
            var list = json.data.list;
            obj_key_find('qContent', json, function(msg) {
                console.log("问题：" + msg);
            });
            obj_key_find('item1', json, function(msg) {
                console.log("选项：" + msg);
            });
            obj_key_find('item2', json, function(msg) {
                console.log("答案：" + msg);
                msg = msg.replace(/\[|\]/g, '');;
                if (msg.match(/没有找到问题/) == null) {
                    console.log('去匹配选项');
                    setTimeout(() => select(undefined, msg), rd(300, 500));
                } else if (msg.match(/没有找到问题/) && err <= 1) {
                    err++;
                    console.log('再试' + err + '次');
                    value = title.slice(0, 30);
                    if (err == 2) {
                        value = title.slice(0, 20);
                    } else {
                        value = title.slice(0, 10);
                    }
                    console.log(value);
                    setTimeout(() => goto_enc(title.slice(0, 30), err), rd(300, 500));
                } else {
                    console.log('去问AI');
                    getAccessToken();
                }
            });
        }
    });
}

function getAccessToken() {
    var token;
    var AK = "TowOHAGOKouwA6N2KwqCY8pD";
    var SK = "s0I5jBwiHVV0REX3MNuwLthdB78MjIXF";
    $.ajax({
        type: "POST",
        url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        data: 'cookie=' + 'cookie:asfsdrer',
        error: function(data) {
            console.log(JSON.stringify(data));
        },
        success: function(data) {
            token = data.access_token;
            console.log('获取到token:', token);
            if (token) {
                aianswer(token);
            } else {
                console.log('获取token失败了！');
            }
        }
    });
}

function aianswer(token) {
    btn_click = 0;
    var question = $('#subjectType').text() + ':' + $('#subjectName').text().replace(/\d+、/, '');
    var options = $('#subjectItems').text();
    console.log("问题：", question);
    console.log("选项：", options);
    $.ajax({
        timeout: 30000,
        type: "POST",
        'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' + token,
        'headers': {
            'Content-Type': 'application/json'
        },
        data: JSON.stringify({
            "messages": [{
                "role": "user",
                "content": "你是一个答题助手，根据题目：{" + question + "}，从选项：{" + options + "}选择出正确的答案，不需要解析",
                "key": "3"
            }],
            "temperature": 0.8,
            "top_p": 0,
            "penalty_score": 1,
            "disable_search": false,
            "enable_citation": false,
            "collapsed": true,
            "system": "你是一个答题助手，根据题目和选项，从选项返回正确答案，不需要解析"
        }),
        error: function(data) {
            console.log(JSON.stringify(data));
            console.log('AI请求答案失败了！');
        },
        success: function(data) {
            console.log(JSON.stringify(data));
            console.log(data.result);
            if (data.result && data.result) {
                var text = data.result;
                console.log("答案：", text);
                select(text, text, "AI");
            } else {
                console.log('AI好像也不知道这道题的答案');
            }
        }
    });
}

function obj_key_find(findkey, obj, callback_function) {
    for (var key in obj) {
        var value = obj[key];
        if (typeof value == "object") {
            obj_key_find(findkey, value, callback_function);
        }
        if (key == findkey) {
            if (callback_function) callback_function(value);
            return;
        }
    }
}

function jsenc(text, callback) {
    var key = CryptoJS.enc.Utf8.parse('105A856B81F747DF');
    var iv = CryptoJS.enc.Utf8.parse('105A856B81F747DF');
    var modele = {
        keySize: 128,
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    };
    if (typeof text == 'object') {
        text = JSON.stringify(text);
    }
    var data = CryptoJS.enc.Utf8.parse(text);
    var encrypted = CryptoJS.AES.encrypt(data, key, modele).toString();
    var encry_code = encodeURIComponent(encrypted);
    console.log(encrypted);
    if (callback) {
        callback(encry_code)
    }
    return encry_code;
}

function generateRandomHex(length) {
    var result = '';
    var characters = '0123456789abcdef';
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}

function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    str = unescape(str);
    str = str.replace(/%/g, "\\");
    str = str.replace(/\\/g, "");
    return str;
}

function obj_find(obj, callback_function) {
    for (var key in obj) {
        var value = obj[key];
        if (typeof value == "object") {
            obj_find(value, callback_function);
        }
        if (key == 'qid_str') {
            callback_function(value);
            return;
        }
    }
}
var btn_click = 0;

function rdabd() {
    var cparr = ['a', 'b', 'c', 'd'];
    return cparr[rd(0, 4)];
}

function select(_abc, _text, op) {
    var t = 0;
    var s = 0;
    var xx = $('.answer-items.mydefitems');
    if (xx && xx.length > 0) {
        test_click(0);
    }

    function test_click(i) {
        var text = $('.answer-items.mydefitems')[i] && $($('.answer-items.mydefitems')[i]) && $($('.answer-items.mydefitems')[i]).text();
        text = text.replace(/\s/g, '.*');
        _text = _text && _text.replace(/\s/g, '.*');
        var abc = text.match(/[a-z]/) && text.match(/[a-z]/)[0];
        text = text.replace(abc, '');
        console.log(text, _text);
        if (text && _text && (text.match(RegExp(_text, 'i')) || _text.match(RegExp(text, 'i')))) {
            console.log('匹配成功', text, _text);
            if ($('.answer-items.mydefitems')[i].outerHTML.match(/primary/)) {
                console.log('此选项已经选择！');
            } else {
                $($('.answer-items.mydefitems')[i]).click();
            }
            t++;
            console.log(abc, text);
        } else if (_abc && abc && (_abc.match(RegExp(abc, 'i')) || abc.match(RegExp(_abc, 'i')))) {
            if ($('.answer-items.mydefitems')[i].outerHTML.match(/primary/)) {
                console.log('此选项已经选择！');
            } else {
                $($('.answer-items.mydefitems')[i]).click();
            }
            t++;
            console.log(abc, text);
        }
        i++;
        if (i < xx.length) {
            setTimeout(() => test_click(i), 50);
        } else {
            if (t > 0) {
                btn_click++;
                console.log('选择了' + t + '个答案，匹配到' + btn_click + '次');
                if (btn_click == 1) {
                    if ($('.noanswer').length == 0) {
                        timer_submit();
                    } else {
                        next();
                    }
                }
            } else {
                btn_click++;
                if (btn_click == 1 && op == undefined) {
                    console.log('好像没有匹配到答案呢，去问下AI吧');
                    getAccessToken();
                } else {
                    console.log('AI给的答案好像匹配不出正确选项');
                }
            }
        }
    }
    setTimeout(() => {
        if (t == 0) {}
    }, 2000);
}

function next() {
    setTimeout(() => $('#btnConfirm').click(), 200);
    setTimeout(() => {
        if (title != get_tm()) {
            title = get_tm();
            var test_text = title.slice(0, 30);
            btn_click = 0;
            if (tiku == 0) {
                goto_enc(test_text, 0);
            } else if (tiku == 1) {
                post(title);
            }
        }
    }, 500);
}

function get_verify_code(callback) {
    var url = "https://api.cloud.tencent.com/requesttc3";
    var jsondata = JSON.stringify({
        "ImageBase64": getimgbase64()
    });
    var sub_data = {
        "Product": "ocr",
        "Action": "GeneralAccurateOCR",
        "Version": "2018-11-19",
        "Region": "ap-guangzhou",
        "Area": "",
        "SecretId": "AKIDoOlrhHFJdrphLkNykESMN9dsqYlngw82",
        "SecretKey": "sJAn9HRM8frpZ0d10kIsDG2eBakfiVzE",
        "JsonData": jsondata,
        "Language": "zh-CN"
    };
    $.ajax({
        url: url,
        type: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json, text/javascript, */*; q=0.01",
        },
        /*timeout : 10000,*/ data: jsontourl(sub_data),
        dataType: 'json',
        success: function(obj) {
            var code = obj.body && obj.body.Response && obj.body.Response.TextDetections && obj.body.Response.TextDetections[0] && obj.body.Response.TextDetections[0].DetectedText;
            if (code) {
                code = code.replace(/\s/g, '');
                console.log('识别到验证码：', code);
                $("#verifyCode").val(code);
                code = code.toUpperCase();
                $.cookie("vkc", code);
                if (callback) {
                    callback();
                }
            } else {
                console.log(obj);
            }
        }
    })
}

function jsontourl(json) {
    var url = Object.keys(json).map(function(key) {
        return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }).join("&");
    return url;
}

function getimgbase64() {
    var img = document.querySelector('#verifyImg');
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var base64Image = canvas.toDataURL();
    console.log(base64Image);
    return base64Image;
}

function submit_answer() {
    clickNext();
    var storeExamInfoStr = localStorage.getItem("exam_info_" + $.cookie("cookie_a_userId") + "_" + examInfoId);
    var jsonVal = JSON.parse(storeExamInfoStr);
    var singles = '',
        multis = '',
        bools = '';
    let orderArr = jsonVal.order;
    if (orderArr !== undefined) {
        for (let i = 0; i < orderArr.length; i++) {
            let key = orderArr[i];
            let value = jsonVal.param.singleMap[key];
            if (value === undefined) {
                continue
            }
            singles += orderArr[i] + ":" + value + ','
        }
        for (let i = 0; i < orderArr.length; i++) {
            let key = orderArr[i];
            let value = jsonVal.param.multiMap[key];
            if (value === undefined) {
                continue
            }
            multis += orderArr[i] + ":" + value + ','
        }
        for (let i = 0; i < orderArr.length; i++) {
            let key = orderArr[i];
            let value = jsonVal.param.boolMap[key];
            if (value === undefined) {
                continue
            }
            bools += orderArr[i] + ":" + value + ',';
        }
    } else {
        for (var key in jsonVal.param.singleMap) {
            singles += key + ':' + jsonVal.param.singleMap[key] + ',';
        }
        for (var key in jsonVal.param.multiMap) {
            multis += key + ':' + jsonVal.param.multiMap[key] + ',';
        }
        for (var key in jsonVal.param.boolMap) {
            bools += key + ':' + jsonVal.param.boolMap[key] + ','
        }
    } if (singles != '') {
        singles = singles.substring(0, singles.length - 1);
    }
    if (multis != '') {
        multis = multis.substring(0, multis.length - 1);
    }
    if (bools != '') {
        bools = bools.substring(0, bools.length - 1);
    }
    jsonVal.param.singles = singles;
    jsonVal.param.bools = bools;
    jsonVal.param.multis = multis;
    jsonVal.param.userIsFinish = 1;
    if ($('.noanswer').length == 0) {
        var param = {
            'submitId': jsonVal.param.submitId,
            'examId': examInfoId,
            'examPaperId': jsonVal.param.examPaperId,
            'singles': singles,
            'booleans': bools,
            'multiples': multis,
            'submitTime': new Date().getTime()
        };
        callRemoteMethod(api.userSubmitNewExamPaperUrl, param, submitCallBack);
    }
}
var rd_submit_timer = rd2(10800 - 600, 10800 - 900);
var timer1 = setInterval(timer_submit, 1000);

function timer_submit() {
    if ($('.noanswer').length > 0) {} else if (window.countDownSecond && countDownSecond < rd_submit_timer && $('.noanswer').length == 0) {
        console.log("时间段到了，准备交卷");
        clearInterval(timer1);
        submit_answer();
    } else {
        console.log('已经做完了，等待交卷~');
    }
}